
 <!DOCTYPE HTML>
<html lang="ch">
<head>
  <meta charset="UTF-8">
  
    <title>使用Java进行文本加密 | Yuan</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="Luo Yuan">
    

    
    <meta name="description" content="通用的加密模式可以分为对称加密、不对称加密、单向加密（不可逆加密）。偶然想要查询下如何在java中进行文本加密，网上搜索到的都是大篇幅介绍加密原理，如何使用却都是一句话带过，真真是看着就烦。所以本文不涉及加密原理和概念，只是列举了如何使用java进行三种方式加密的例子，作为参考使用。">
<meta property="og:type" content="article">
<meta property="og:title" content="使用Java进行文本加密">
<meta property="og:url" content="http://luoyuan800.github.io/2015/07/22/encode-java/index.html">
<meta property="og:site_name" content="Yuan">
<meta property="og:description" content="通用的加密模式可以分为对称加密、不对称加密、单向加密（不可逆加密）。偶然想要查询下如何在java中进行文本加密，网上搜索到的都是大篇幅介绍加密原理，如何使用却都是一句话带过，真真是看着就烦。所以本文不涉及加密原理和概念，只是列举了如何使用java进行三种方式加密的例子，作为参考使用。">
<meta property="og:locale">
<meta property="article:published_time" content="2015-07-22T07:58:00.000Z">
<meta property="article:modified_time" content="2021-04-22T08:07:19.949Z">
<meta property="article:author" content="Luo Yuan">
<meta name="twitter:card" content="summary">

    
    <link rel="alternative" href="/atom.xml" title="Yuan" type="application/atom+xml">
    
    
    <link rel="icon" href="/img/favicon.ico">
    
    
    <link rel="apple-touch-icon" href="/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/jacman.jpg">
    
    
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/%02.css">
<link rel="stylesheet" href="/.css">

<meta name="generator" content="Hexo 5.4.0"></head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/"><img src="/img/logo.png" alt="Yuan" title="Yuan"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/" title="Yuan">Yuan</a></h1>
				<h2 class="blog-motto">一点一滴，积累技术</h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/">Home</a></li>
					
						<li><a href="/archives">Archives</a></li>
					
						<li><a href="/about">About</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:luoyuan800.github.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/2015/07/22/encode-java/" title="使用Java进行文本加密" itemprop="url">使用Java进行文本加密</a>
  </h1>
  <p class="article-author">By
       
		<a href="/about" title="Luo Yuan" target="_blank" itemprop="author">Luo Yuan</a>
		
  <p class="article-time">
    <time datetime="2015-07-22T07:58:00.000Z" itemprop="datePublished"> Published 2015-07-22</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#MD5"><span class="toc-number">1.</span> <span class="toc-text">MD5</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#AES"><span class="toc-number">2.</span> <span class="toc-text">AES</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A0%E5%AF%86"><span class="toc-number">2.1.</span> <span class="toc-text">加密</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%A3%E5%AF%86"><span class="toc-number">2.2.</span> <span class="toc-text">解密</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RSA"><span class="toc-number">3.</span> <span class="toc-text">RSA</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A0%E5%AF%86-1"><span class="toc-number">3.1.</span> <span class="toc-text">加密</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%A3%E5%AF%86-1"><span class="toc-number">3.2.</span> <span class="toc-text">解密</span></a></li></ol></li></ol>
		
		</div>
		
		<p>通用的加密模式可以分为对称加密、不对称加密、单向加密（不可逆加密）。偶然想要查询下如何在java中进行文本加密，网上搜索到的都是大篇幅介绍加密原理，如何使用却都是一句话带过，真真是看着就烦。所以本文不涉及加密原理和概念，只是列举了如何使用java进行三种方式加密的例子，作为参考使用。<span id="more"></span></p>
<h2 id="MD5"><a href="#MD5" class="headerlink" title="MD5"></a>MD5</h2><p>不可逆加密指的是使用MD5或者SHA进行加密，其本质是抽取特征码，抽取出来的密文是不可逆向解密回原来的文本的。这种方式大多用于密码的存储——只在数据库中存储抽取的特征码，而不存储原来的密码。</p>
<pre><code>MessageDigest md5 = MessageDigest.getInstance(&quot;MD5&quot;);

BASE64Encoder base64Encoder = new BASE64Encoder();

String info = base64Encoder.encode(md5.digest(&quot;luoyuan&quot;.getBytes(&quot;utf-8&quot;)));

System.out.println(info);
</code></pre>
<p>其中<code>getInstance(String)</code>的取值是限定的，如果传入的不是以下的字符串之一，就会抛出<code>NoSuchAlgorithmException</code></p>
<ul>
<li><p>MD5</p>
</li>
<li><p>MD2</p>
</li>
<li><p>SHA-1</p>
</li>
<li><p>SHA-256</p>
</li>
<li><p>SHA-384</p>
</li>
<li><p>SHA-512</p>
</li>
</ul>
<h2 id="AES"><a href="#AES" class="headerlink" title="AES"></a>AES</h2><p>AES和DES的使用方式在Java中都差不多，所以不在此处提及DES的使用范例。</p>
<p>AES加密方式属于对称加密，加密和解密都需要使用一样的密钥。所以在加密时候使用的密钥要和密文一起发送。</p>
<h3 id="加密"><a href="#加密" class="headerlink" title="加密"></a>加密</h3><pre><code>String mess = &quot;luoyuan&quot;;

KeyGenerator keyGenerator = KeyGenerator.getInstance(&quot;AES&quot;);//获取一个AES相关的KeyGenerator

keyGenerator.init(128);//指定生成密钥的长度为128

SecretKey key = keyGenerator.generateKey();//生成一个密钥

Cipher cipher = Cipher.getInstance(&quot;AES/ECB/PKCS5Padding&quot;);//构建Cipher,设置模式，解密的时候也必须使用同样的模式

cipher.init(Cipher.ENCRYPT_MODE, key);//使用生成的密钥初始化

byte[] encode = cipher.doFinal(mess.getBytes(&quot;utf-8&quot;));//执行加密过程

System.out.println(Arrays.toString(encode));
</code></pre>
<h3 id="解密"><a href="#解密" class="headerlink" title="解密"></a>解密</h3><pre><code>byte[] keyCode = &#123;...&#125;;//加密过程生成的密钥的encoded

byte[] data = &#123;...&#125;;//加密后的文本字节数组

SecretKey key = new SecretKeySpec(keyCode, &quot;AES&quot;);//根据给出的密钥（字节数组）生成一个Key对象

Cipher cipher = Cipher.getInstance(&quot;AES/ECB/PKCS5Padding&quot;); //生成一个和加密时候使用的模式一样的Cipher

cipher.init(Cipher.DECRYPT_MODE, key);

byte[] decode = cipher.doFinal(data);//执行解密步骤

System.out.println(new String(decode));
</code></pre>
<h2 id="RSA"><a href="#RSA" class="headerlink" title="RSA"></a>RSA</h2><p>RSA(DSA)加密属于非对称加密，加密解密过程会使用到不同的密钥——公钥和私钥。</p>
<p>如果使用公钥加密，那么解密可以使用私钥解密，如果使用私钥加密，则必须使用公钥进行解密。</p>
<h3 id="加密-1"><a href="#加密-1" class="headerlink" title="加密"></a>加密</h3><pre><code>String msg = &quot;Luoyuan&quot;;

KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(&quot;RSA&quot;);//初始化一个KeyPairGenerator

keyGenerator.initialize(1024);//设置密钥长度为1024

KeyPair keyPair = keyGenerator.generateKeyPair();//RSA加密需要生成相对应的公钥和私钥

RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();//获得私钥

RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();//获得公钥

Cipher cipher = Cipher.getInstance(&quot;RSA&quot;);

cipher.init(Cipher.ENCRYPT_MODE, publicKey);//使用私钥加密

byte[] encode = cipher.doFinal(msg.getBytes(&quot;utf-8&quot;));

System.out.println(Arrays.toString(encode));
</code></pre>
<h3 id="解密-1"><a href="#解密-1" class="headerlink" title="解密"></a>解密</h3><pre><code>byte[] publicKeyCode = &#123;...&#125;;

byte[] encode = &#123;...&#125;;

Cipher cipher = Cipher.getInstance(&quot;RSA&quot;);

RSAPublicKey publicKey = new RSAPublicKeyImpl(publicKeyCode);//根据公钥的encode构建公钥对象

cipher.init(Cipher.DECRYPT_MODE, publicKey);//使用公钥解密

byte[] decode = cipher.doFinal(encode);

System.out.println(new String(decode));
</code></pre>
  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/categories/%E7%BC%96%E7%A8%8B-Java/">编程-Java</a>
</div>


</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://luoyuan800.github.io/2015/07/22/encode-java/" data-title="使用Java进行文本加密 | Yuan" data-tsina="" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/2015/07/23/jvm-gc/" title="JVM 垃圾回收器">
  <strong>上一篇：</strong><br/>
  <span>
  JVM 垃圾回收器</span>
</a>
</div>


<div class="next">
<a href="/2015/07/15/regex-java/"  title="正则表达式进阶">
 <strong>下一篇：</strong><br/> 
 <span>正则表达式进阶
</span>
</a>
</div>

</nav>

	



</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#MD5"><span class="toc-number">1.</span> <span class="toc-text">MD5</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#AES"><span class="toc-number">2.</span> <span class="toc-text">AES</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A0%E5%AF%86"><span class="toc-number">2.1.</span> <span class="toc-text">加密</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%A3%E5%AF%86"><span class="toc-number">2.2.</span> <span class="toc-text">解密</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RSA"><span class="toc-number">3.</span> <span class="toc-text">RSA</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A0%E5%AF%86-1"><span class="toc-number">3.1.</span> <span class="toc-text">加密</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%A3%E5%AF%86-1"><span class="toc-number">3.2.</span> <span class="toc-text">解密</span></a></li></ol></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/categories/杂物-医学/" title="杂物-医学">杂物-医学<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-Java/" title="编程-Java">编程-Java<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-Linux-Unix/" title="编程-Linux/Unix">编程-Linux/Unix<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-工具/" title="编程-工具">编程-工具<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-网络协议/" title="编程-网络协议">编程-网络协议<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/categories/网站-开发/" title="网站-开发">网站-开发<sup>2</sup></a></li>
		  
		
		</ul>
</div>


  

  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=&verifier=&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m Luo Yuan in Zhuhai. <br/>
			Here is my place for knowledge accumulation.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2021 
		
		<a href="/about" target="_blank" title="Luo Yuan">Luo Yuan</a>
		
		
		</p>
</div>
</footer>
    <script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>
<script src="/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>











<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/img/scrollup.png"/></a>
	</div>
	<script src="/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
